<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------
use think\Db;
// 应用公共文件
/**
 * 获取客户端IP地址
 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @param boolean $adv 是否进行高级模式获取（有可能被伪装）
 * @return mixed
 */
function get_client_ip($type = 0, $adv = false)
{
    $type = $type ? 1 : 0;
    //static $ip  =   NULL;
    // if ($ip !== NULL) return $ip[$type];
    if ($adv) {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos = array_search('unknown', $arr);
            if (false !== $pos) unset($arr[$pos]);
            $ip = trim($arr[0]);
        } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
        if ($ip == '127.0.0.1') {
            $ip = get_client_ip(0, true);
        }
    }
    // IP地址合法验证
    $long = sprintf("%u", ip2long($ip));
    $ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}

/**
 * 字符串截取，支持中文和其他编码
 * static
 * access public
 * @param string $str 需要转换的字符串
 * @param string $length 截取长度
 * @param string $start 开始位置
 * @param string $charset 编码格式
 * @param string $suffix 截断显示字符
 * return string
 */
function msubstr($str,$length, $start=0, $charset="utf-8", $suffix=true) {
	if(function_exists("mb_substr")){
		$slice = mb_substr($str, $start, $length, $charset);
		$strlen = mb_strlen($str,$charset);
	}elseif(function_exists('iconv_substr')){
		$slice = iconv_substr($str,$start,$length,$charset);
		$strlen = iconv_strlen($str,$charset);
	}else{
		$re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
		$re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
		$re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
		$re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
		preg_match_all($re[$charset], $str, $match);
		$slice = join("",array_slice($match[0], $start, $length));
		$strlen = count($match[0]);
	}
	if($suffix && $strlen>$length)$slice.='...';
	return $slice;
}

// 验证短信验证码
// $code 验证码
// $phone 手机号码
// $type 短信类型  1、注册； 2、登录； 3、找回密码； 4
function check_note_code($code, $phone, $type) {
//    if($code == 123456) {
//        return ['data' => '', 'code' => 200, 'msg' => 'SUCCESS'];
//    }
//    Db::listen(function($sql, $time, $explain){
//        // 记录SQL
//        echo $sql. ' ['.$time.'s]';
//    });
    $where = [
        'code' => $code,
        'phone' => $phone,
        'type' => $type
    ];
    $code = Db::table('mob_note_code')->where($where)->order('id desc')->find();
    if(!$code)  return ['data' => '', 'code' => 400006, 'msg' => 'FAULT'];
    if($code['status'] > 0) return ['data' => '', 'code' => 400007, 'msg' => 'FAULT'];
    if($code['add_time'] < (time() - 600)) return ['data' => '', 'code' => 400008, 'msg' => 'FAULT'];

    //将验证码状态改为已使用
    Db::table('mob_note_code')->where($where)->update(['status' => 1]);

    return ['data' => '', 'code' => 200, 'msg' => 'SUCCESS'];
}

// 获取上级市场线
function get_parents($parent_phone) {
    $parent = db('member')->where('phone', $parent_phone)->find();
    if (!$parent) {
        return false;
    }
    return [
        'parents' => $parent['parents'] ? $parent['parents'] . ',' . $parent['id'] : $parent['id'],
        'id' => $parent['id']
    ];
}

// 获取半径范围内的经纬度
// $lat 纬度
// $lon 经度
// $raidus 半径米
function getAround($lat, $lon, $radius){
    $PI = 3.14159265;
    $latitude = $lat;
    $longitude = $lon;

    $degree = (24901*1609)/360.0;
    $radiusMile = $radius;

    $dpmLat = 1/$degree;
    $radiusLat = $dpmLat*$radiusMile;
    $minLat = $latitude - $radiusLat;
    $maxLat = $latitude + $radiusLat;

    $mpdLng = $degree*cos($latitude * ($PI/180));
    $dpmLng = 1 / $mpdLng;
    $radiusLng = $dpmLng*$radiusMile;
    $minLng = $longitude - $radiusLng;
    $maxLng = $longitude + $radiusLng;
    return [$minLat, $maxLat, $minLng, $maxLng];
}


function newRichText($name){
    $a = <<<TexT
<script type="text/javascript" src="/static/ueditor/ueditor.config.js"></script>
<script type="text/javascript" src="/static/ueditor/ueditor.all.min.js"></script>
<script type="text/javascript" src="/static/ueditor/lang/zh-cn/zh-cn.js"></script>
<script type="text/javascript">
    var ueditoroption = {
        'autoClearinitialContent': false,
        'toolbars': [['fullscreen', 'source', 'preview', '|', 'bold', 'italic', 'underline', 'strikethrough', 'forecolor', 'backcolor', '|',
            'justifyleft', 'justifycenter', 'justifyright', '|', 'insertorderedlist', 'insertunorderedlist', 'blockquote', 'emotion', 'insertvideo',
            'link', 'removeformat', '|', 'rowspacingtop', 'rowspacingbottom', 'lineheight', 'indent', 'paragraph', 'fontsize', '|',
            'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol',
            'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', '|', 'anchor', 'map', 'print', 'drafts']],
        'elementPathEnabled': false,
        'initialFrameHeight': 200,
        'focus': false,
        'maximumWords': 9999999999999
    };
    var opts = {
        type: 'image',
        direct: false,
        multi: true,
        tabs: {
            'upload': 'active',
            'browser': '',
            'crawler': ''
        },
        path: '',
        dest_dir: '',
        global: false,
        thumb: false,
        width: 0
    };
    UE.registerUI('myinsertimage', function (editor, uiName) {
        editor.registerCommand(uiName, {
            execCommand: function () {
                require(['fileUploader'], function (uploader) {
                    uploader.show(function (imgs) {
                        if (imgs.length == 0) {
                            return;
                        } else if (imgs.length == 1) {
                            editor.execCommand('insertimage', {
                                'src': imgs[0]['url'],
                                '_src': imgs[0]['attachment'],
                                'width': '100%',
                                'alt': imgs[0].filename
                            });
                        } else {
                            var imglist = [];
                            for (i in imgs) {
                                imglist.push({
                                    'src': imgs[i]['url'],
                                    '_src': imgs[i]['attachment'],
                                    'width': '100%',
                                    'alt': imgs[i].filename
                                });
                            }
                            editor.execCommand('insertimage', imglist);
                        }
                    }, opts);
                });
            }
        });
        var btn = new UE.ui.Button({
            name: '插入图片',
            title: '插入图片',
            cssRules: 'background-position: -726px -77px',
            onclick: function () {
                editor.execCommand(uiName);
            }
        });
        editor.addListener('selectionchange', function () {
            var state = editor.queryCommandState(uiName);
            if (state == -1) {
                btn.setDisabled(true);
                btn.setChecked(false);
            } else {
                btn.setDisabled(false);
                btn.setChecked(state);
            }
        });
        return btn;
    }, 19);

    $(function () {
        var ue = UE.getEditor("$name", ueditoroption);
        $("#$name").data('editor', ue);
        $("#$name").parents('form').submit(function () {
            if (ue.queryCommandState('source')) {
                ue.execCommand('source');
            }
        });
    });
</script>

TexT;
    return $a;
}


function upload($filename,$value,$loadLib = true, $width=260, $height=200, $url='/index.php/admin/Upload/uploadify'){
    if(empty($value)){
        $value='/uploads/empty.png';
    }
    $lib = <<<LIB
	<script src="/admin/template1/global/plugins/jquery.min.js" type="text/javascript"></script>
	<link href="/static/uploadify/uploadify.css" rel="stylesheet" type="text/css" />
	<script type="text/javascript" src="/static/uploadify/jquery.uploadify.min.js"></script>
LIB;

    $html = '';
    if($loadLib){
        $html .= $lib;
    }

    $html .= <<<TexT
	<div style="width: {$width}px;height: {$height}px;">
		<img id="{$filename}img" style="width: {$width}px;height: {$height}px;" border=0 src='{$value}'/>
	</div>
	<input name="{$filename}" type="file"  for="img" id="{$filename}"/>
	<input id="{$filename}url" name="{$filename}" type="hidden" value="{$value}"/>
	<script type="text/javascript">
		$("#{$filename}").uploadify({
			'buttonText': '点击上传',
			'multi': false,//只能传一个文件
			'width':'260',
			'removeTimeout':0,//完成后移除弹出框的时间间隔
			'fileTypeExts': '*.jpg; *.jpeg; *.png;',
			'swf': "/static/uploadify/uploadify.swf",
			'button_image_url': "",
			'uploader': "{$url}",
			'onUploadSuccess': function (file, data, response) {
				var rs = JSON.parse(data);
				if (rs.success == true) {
					$('#{$filename}img').attr('src', rs.data.url);
					$('#{$filename}url').val(rs.data.url);
				}
			}
		});
	</script>
TexT;

    return $html;
}

/**
 * 售后状态
 */
function get_order_austin_status($status, $type)
{
    if ($type == 1) // 退款
        $statusText = ['退款中', '同意退款', '拒绝退款', '已取消', '申请仲裁', '已结束'];
    else
        $statusText = ['售后中', '同意售后', '拒绝售后', '已取消', '申请仲裁', '已结束'];
    return $statusText[$status];
}

/**
 * 服务单状态
 */
function get_order_server_status($status)
{
    // 1下单成功； 2待付款；  3已付款； 4、服务中；  5待确认； 6订单完成； 7.订单结束（已过售后期） 9订单取消；  11议价中
    $statusText = [
        1 => '下单成功',
        2 => '待付款',
        3 => '已付款',
        4 => '工作完成',
        5 => '待确认',
        6 => '订单完成',
        7 => '交易完成',
        9 => '订单取消',
        11 => '议价中',
    ];
    return $statusText[$status];
}

function get_order_server_after_sale_status($status)
{
    $statusText = [
        0 => '',
        1 => '申请退款',
        2 => '申请售后',
        3 => '申请仲裁',
        4 => '售后完成',
    ];
    return $statusText[intval($status)];
}

// 获取性别
function get_sex($sex) {
    $sex_array = ['保密', '男', '女'];
    return $sex_array[$sex];
}

// 获取代理级别
function get_level($level) {
    $level_array = ['', '省', '市', '区', '街道'];
    return $level_array[$level];
}

// 获取审核状态
function audit_status($status) {
    $status_array = ['', '提交申请', '合伙人审核通过', '合伙人审核未通过', '平台审核通过', '平台审核未通过', '已关闭'];
    return $status_array[$status];
}

// 获取合伙人帐号
function get_auditor($id) {
    if ($id === 0) {
        return '平台审核';
    }
    return db('partner')->where('id', $id)->value('proposer');
}

// 获取服务单状态
function get_server_order_status($value) {
    $status = [
        0=>'临时单',
        1=>'已下单',
        2=>'待付款',
        3=>'已付款',
        4=> '服务中',
        5=>'待确认',
        6=>'订单完成',
        7=>'订单结束（已过售后期）',
        8=> '申请仲裁中',
        9=>'订单取消',
        10=> '已完成',//已评价
        11=>'议价中',
    ];
    return $status[$value];
}

// 获取服务单评价状态
function get_order_comment_status($value) {
    $status = [
        '未评价','已评价'
    ];
    return $status[$value];
}

// 获取服务单售后状态
function get_order_after_sale_status($value) {
    $status = [
        '暂无售后', '申请退款', '申请退货', '申请仲裁', '售后结束',
    ];
    return $status[$value];
}
// 获取产品类型
function get_product_type($value) {
    $status = [
        '', '产品库产品', '自有产品', '服务产品'
    ];
    return $status[$value];
}
// 获取消息类型
function get_msg_type($value) {
    $status = [
        '', '系统', '订单', '活动'
    ];
    return $status[$value];
}
// 获取消息类型
function get_creator($value) {
    $status = [
        '平台', '维修店', '经销商', '合伙人', '店铺'
    ];
    return $status[$value];
}

// 获取用户类型
function get_member_type($value) {
    $status = [
        '用户端', '维修店', '经销商', '合伙人'
    ];
    return $status[$value];
}

// 获取用户类型
function get_fund_account_type($value) {
    $status = [
        '', '支付宝', '微信', '银行卡'
    ];
    return $status[$value];
}

// 获取用户反馈状态
function get_feedback_status($value) {
    $status = [
        '未查看', '已查看'
    ];
    return $status[$value];
}
// 获取优惠券类型
function get_coupon_type($value) {
    $status = [
        '平台', '店铺', '维修店'
    ];
    return $status[$value];
}
// 获取服务单售后状态服务方式
function get_service_mode($value) {
    $status = [
        '', '到店', '上门'
    ];
    return $status[$value];
}

// 获取省市区
function get_region($id) {
    $str = "";
    if( intval($id) ) {
        $str = db('region')->where('region_id',$id)->whereOr('sNum',$id)->value('region_name');
    }
    if(!$str){
        $str = $id;
    }
    return $str;
}

// 以POST方式提交数据
function post_data($url, $data) {
    $ch = curl_init ();

    curl_setopt ( $ch, CURLOPT_URL, $url);
    curl_setopt ( $ch, CURLOPT_POST, 1 );
    curl_setopt ( $ch, CURLOPT_HEADER, 0 );
    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
    if($data) {
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, 'data=' . $data );
    } else {
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, '' );
    }

    $res = curl_exec ( $ch );
    curl_close ( $ch );

    //$return_array && $res = json_decode ( $res, true );

    return $res;
}

// 以GET方式提交数据
function get_data($url) {

    $ch = curl_init($url) ;
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ; // 获取数据返回
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ; // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回

    $res = curl_exec ( $ch );

    curl_close ( $ch );

    //$return_array && $res = json_decode ( $res, true );

    return $res;
}

// 添加系统日志
function add_system_log($msg) {
    db('system_log')->insert(['msg' => $msg, 'add_time' => time()]);
}

/*
*功能：php完美实现下载远程图片保存到本地
*参数：文件url,保存文件目录,保存文件名称，使用的下载方式
*当保存文件名称为空时则使用远程文件原来的名称
*/
function getImage($url,$filename='',$save_dir='uploads/bank/logo/',$type=0){
    if(trim($url)==''){
        return array('file_name'=>'','save_path'=>'','error'=>1);
    }
    if(trim($save_dir)==''){
        $save_dir='./';
    }
    if(trim($filename)==''){//保存文件名
        $ext=strrchr($url,'.');
        if($ext!='.gif'&&$ext!='.jpg'){
            return array('file_name'=>'','save_path'=>'','error'=>3);
        }
        $filename=time().$ext;
    }
    if(0!==strrpos($save_dir,'/')){
        $save_dir.='/';
    }
    //创建保存目录
    if(!file_exists($save_dir)&&!mkdir($save_dir,0777,true)){
        return array('file_name'=>'','save_path'=>'','error'=>5);
    }
    //获取远程文件所采用的方法
    if($type){
        $ch=curl_init();
        $timeout=5;
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
        $img=curl_exec($ch);
        curl_close($ch);
    }else{
        ob_start();
        readfile($url);
        $img=ob_get_contents();
        ob_end_clean();
    }
    //$size=strlen($img);
    //文件大小
    $fp2=@fopen($save_dir.$filename,'a');
    fwrite($fp2,$img);
    fclose($fp2);
    unset($img,$url);
    return array('file_name'=>$filename,'save_path'=>$save_dir.$filename,'error'=>0);
}

// 获取远程图片并保存到本地
function auto_save_image($body, $file){
    $img_array = explode('&',$body);
    set_time_limit(0);
    $imgPath = "uploads/bank/logo";
    if(!is_dir($imgPath)) @mkdir($imgPath,0777,true);
    foreach($img_array as $key =>$value)
    {
        $value = trim($value);
        $get_file = @file_get_contents($value);
        $rndFileName = $imgPath . $file;
        if($get_file)
        {
            $fp = @fopen($rndFileName,"w");
            @fwrite($fp,$get_file);
            @fclose($fp);
        }
        $body = @ereg_replace($value, $rndFileName, $body);
    }

    return $body;
}

// 新订单消息推送模板
function new_order_push_msg($params) {
    $url = 'http://'.$_SERVER["HTTP_HOST"].'/wechat/r_member/order_info.html?id=' . $params['order_id'];

    // 发送短信
    if (isset($params['m_phone']) && $params['m_phone']) {
        $param = [
            'phone' => $params['m_phone'],
            'type' => 31,
            'model' => 3053108
        ];
        \app\api\service\Common::send_note($param);
    }

    // 发送微信模板消息
    if (isset($params['openid']) && $params['openid']) {
        $data = [
            'touser' => $params['openid'],
            'template_id' => 'rnJUnlEzUqYEEwmXLKm-U2LpMW90D-7l71DqIzp4tkY',
            'url' => $url,
            'topcolor' => '#FF0000',
            'data' => [
                'first' => [
                    'value' => '新订单提醒',
                    "color" => "#173177"
                ],
                'keyword1' => [
                    'value' => '发现一笔新订单',
                    "color" => "#173177"
                ],
                'keyword2' => [
                    'value' => date('Y-m-d H:i:s'),
                    "color" => "#173177"
                ],
                'remark' => [
                    'value' => '请尽快处理',
                    "color" => "#173177"
                ]
            ]
        ];
        send_msg($data);
    }

    /*****
     * 推送站内信息 *  ****/
    $param = [
        'member_id' => $params['member_id'],
        'member_role' => 'repair',
        'msg_id' => 43,
        'data' => [
            $params['order_sn'], date('Y-m-d H:i:s'), 'url' => $url, 'id' => $params['order_id'], 'action' => 1
        ]
    ];
    \app\api\service\Message::creation_order_msg($param);
    /***** * 推送站内信息 --end *  ****/
}


// 微信模版消息
function send_msg($data) {
    $options = config('wechat');
    $wechatObj = new \Wechat\TPWechat($options);
    $access_token = $wechatObj->checkAuth();
    $url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . $access_token;
    post_data($url, json_encode($data)) ;
}

// 验证身份证号码
function checkCardNo($value) {
    $IDCardBody = substr($value, 0, -1);
    $last_num = substr($value, -1);
    if (strlen($IDCardBody) != 17) {
        return false;
    }
    //加权因子
    $factor = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
    //校验码对应值
    $code = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
    $checksum = 0;
    for ($i = 0; $i < strlen($IDCardBody); $i++) {
        $checksum += substr($IDCardBody, $i, 1) * $factor[$i];
    }
    if ($code[$checksum % 11] == $last_num)
        return true;
    else
        return false;
}

// 获取省、市、区、街道对应的ID
function get_scope_id($province, $city, $area, $street) {
    $data['province'] = db('region')->where('region_name', $province)->value('region_id'); //  省肯定存在 直接获取

    $data['city'] = db('region')->where('region_name', $city)->value('region_id');  // 市  如果不存在  添加市区街道
    if (!$data['city']) {
        $data['city'] = db('region')->insertGetId(['parent_id' => $data['province'], 'region_name' => $city, 'region_type' => 2]);
        $data['area'] = db('region')->insertGetId(['parent_id' => $data['city'], 'region_name' => $area, 'region_type' => 3]);
        $data['street'] = db('region')->insertGetId(['parent_id' => $data['area'], 'region_name' => $street, 'region_type' => 4]);
        return $data;
    }

    $data['area'] = db('region')->where('region_name', $area)->value('region_id'); // 区  如果不存在  添加区街道
    if (!$data['area']) {
        $data['area'] = db('region')->insertGetId(['parent_id' => $data['city'], 'region_name' => $area, 'region_type' => 3]);
        $data['street'] = db('region')->insertGetId(['parent_id' => $data['area'], 'region_name' => $street, 'region_type' => 4]);
        return $data;
    }

    $data['street'] = db('region')->where('region_name', $street)->value('region_id'); // 街道  如果不存在  添加街道
    if (!$data['street']) {
        $data['street'] = db('region')->insertGetId(['parent_id' => $data['area'], 'region_name' => $street, 'region_type' => 4]);
        return $data;
    }

    return $data;
}

function is_weixin() {
    if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {
        return true;
    }
    return false;
}

// 调用接口方法
// 接受参数 接口名字， 参数数组, 默认post传递方式
function call_interface($interface, $param = [], $method = 'post') {
    // 定义接口地址
    $url = config('new.interface_url') . 'interface/';

    // 获取时间
    $data = get_data($url . 'get_time');
    $data = json_decode($data, true);
    $time = $data['data']['time'];
    // 参数转为json格式
    if ($param) {
        $param = json_encode($param);
    }
    // 签名
    $sign = md5('timestamp=' .$time . '&key=jgsdfjkfgjs#$%&khs2423hkfh');
    // 组装接口请求连接
    $url = $url . $interface .'?timestamp=' . $time . '&member_ip=127.0.1.1&sign=' . $sign . '&member_id=1';
    // 有分页请求就拼接分页参数
    if (input('?param.page') && input('param.page') > 1) {
        $url .= '&page=' . input('param.page');
    }
    // 将请求方式转为小写
    $method = strtolower($method);
    if ($method == 'get') {
        $url .= '&data=' . $param;
        $data = get_data($url);
    }
    if ($method == 'post') $data = post_data($url, $param);

    // 将返回的json转为数组
    $data = json_decode($data, true);

    return $data;
}

function get_img_url($img = '') {
    if (!$img) {  // 没有图片使用默认图
        $img = '/static/wechat/images/tui_03.jpg';
    } else {
        if (strpos($img, 'http://') === false) {  // 有图片检查是否有http://
            $img = config('new.interface_url') . $img;   // 没有就拼装图片地址域名
        }
    }
    return $img;
}